<template>
  <Card dis-hover :bordered="false">
    <div class="ivu-text-right">
      <Form inline>
        <Button
          type="primary"
          @click="handleAdd"
          class="ivu-mb-16"
          v-hasC="{
            name: 'v1-rbac-role-create',
            flag: 'v1/rbac/role/create',
          }"
          >新增</Button
        >
      </Form>
    </div>

    <Table
      :columns="columns"
      :data="list"
      :loading="loading"
      :max-height="tableHeigth"
    >
      <template #ctime="{ row }">
        <span>{{ row.created_at_str.slice(0, 10) }}</span>
      </template>
      <template #utime="{ row }">
        <span>{{ row.updated_at_str.slice(0, 10) }}</span>
      </template>
      <template #status_str="{ row }">
        <Badge
          status="success"
          :text="row.status_str"
          v-if="row.status_str === '启用'"
        />
        <Badge status="error" :text="row.status_str" v-else />
      </template>
      <template #action="{ row }">
        <a
          @click="handleRole(row)"
          v-hasC="{
            name: 'v1-rbac-role-update-permission',
            flag: 'v1/rbac/role/update-permission',
          }"
          >权限</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-rbac-role-update-permission',
            flag: 'v1/rbac/role/update-permission',
          }"
        />
        <a
          @click="handleEdit(row)"
          v-hasC="{
            name: 'v1-rbac-role-update2',
            flag: 'v1/rbac/role/update',
          }"
          >编辑</a
        >
        <Divider
          type="vertical"
          v-hasC="{
            name: 'v1-rbac-role-update2',
            flag: 'v1/rbac/role/update',
          }"
        />
        <a
          @click="handleDel(row.id)"
          class="del"
          v-hasC="{
            name: 'v1-rbac-role-delete',
            flag: 'v1/rbac/role/delete',
          }"
          >删除</a
        >
      </template>
    </Table>
    <Page
      class="ivu-mt-16"
      :total="total"
      :modelValue="params.current"
      :page-size="params.size"
      :page-size-opts="pageOpts"
      show-total
      show-sizer
      @on-change="changePage"
      @on-page-size-change="changepageSize"
    />
    <Modal
      :mask-closable="false"
      v-model="addModal"
      :title="edit ? '新增' : '编辑'"
      :footer-hide="true"
      :draggable="true"
    >
      <Form ref="create" :model="roleInfo" :rules="rules" :label-width="60">
        <FormItem label="名称" prop="name" required>
          <Input
            v-model="roleInfo.name"
            placeholder="请输入名称"
            :maxlength="30"
          />
        </FormItem>

        <FormItem label="说明" prop="desc">
          <Input
            v-model="roleInfo.desc"
            type="textarea"
            :rows="4"
            placeholder="请输入说明"
          />
        </FormItem>
        <FormItem label="状态" prop="status">
          <Switch v-model="roleInfo.status" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align: right">
        <Button type="default" @click="addModal = false">取消</Button>
        <Button
          type="primary"
          :loading="btnLoading"
          @click="ok"
          style="margin-left: 10px"
          >确定</Button
        >
      </div>
    </Modal>
    <Drawer
      :closable="true"
      :title="rloeName + '—权限设置'"
      :mask-closable="false"
      width="800"
      v-model="showPermission"
    >
      <tree-table
        class="role"
        :menu-data="rolePermissionList"
        :roledata="rolePermissionList"
        :level="1"
      />

      <div class="pre-drawer-footer ivu-mt-16">
        <Button
          type="default"
          style="margin-right: 8px"
          @click="showPermission = false"
          >取消</Button
        >
        <Button type="primary" @click="handleEditRole" :loading="btnLoading"
          >确定</Button
        >
      </div>
    </Drawer>
  </Card>
</template>
<script>
import treeTable from "./treetable";
import {
  roleList,
  createRole,
  roleInfo,
  updateRole,
  roleDel,
  permissionInfo,
  updatePermission,
} from "@api/role.js";
import { mapState, mapActions } from "vuex";
export default {
  name: "role",
  components: { treeTable },
  data() {
    return {
      tableHeigth: document.body.clientHeight - 270,
      loading: false,
      btnLoading: false,
      addModal: false,
      showPermission: false,
      edit: true,
      params: { current: 1, size: 10 },
      total: 0,
      pageOpts: [10, 20, 30, 40],
      columns: [
        {
          key: "name",
          title: "角色名称",
          minWidth: 125,
        },
        {
          key: "desc",
          title: "说明",
          minWidth: 125,
        },
        {
          slot: "status_str",
          title: "状态",
          minWidth: 80,
        },
        {
          slot: "ctime",
          title: "创建时间",
          minWidth: 120,
        },
        {
          slot: "utime",
          title: "更新时间",
          minWidth: 120,
        },
        {
          slot: "action",
          title: "操作",
          width: 160,
        },
      ],
      list: [],
      roleInfo: {
        id: "",
        name: "",
        desc: "",
        status: true,
      },
      rules: {
        name: [{ required: true, message: "请输入名称" }],
      },
      rolePermissionList: [],
      mymenuIds: [], // 角色菜单
      myactionIds: [], // 角色动作
      roleEditId: "",
      rloeName: "",
    };
  },
  mounted() {
    this.getData();
  },
  computed: {
    ...mapState("power/power", ["menuIds", "actionIds"]),
  },
  methods: {
    ...mapActions("power/power", ["menuIdsAsync", "actionIdsAsync"]),
    //切换page
    changePage(index) {
      this.params.current = index;
      this.getData();
    },
    changepageSize(val) {
      this.params.size = val;
      this.getData();
    },
    handleDel(index) {
      this.$Modal.confirm({
        title: "删除提示",
        content: "是否确认删除此条记录，删除后不可恢复",
        onOk: () => {
          roleDel({ id: index })
            .then(() => {
              this.$Message.success("删除成功");
              this.getData();
            })
            .catch(() => {});
        },
      });
    },
    handleAdd() {
      this.roleInfo = {
        id: "",
        name: "",
        desc: "",
        status: true,
      };
      this.addModal = true;
      this.edit = true;
      this.$refs.create.resetFields();
    },
    handleEdit(info) {
      this.addModal = true;
      this.edit = false;
      roleInfo({ id: info.id })
        .then((res) => {
          this.roleInfo = {
            id: res.id,
            name: res.name,
            desc: res.desc,
            status: res.status == 1 ? true : false,
          };
        })
        .catch(() => {});
    },
    getData() {
      this.loading = true;
      const params = {
        pageSize: this.params.size,
        page: this.params.current,
      };
      roleList(params)
        .then((res) => {
          this.list = res.list;
          this.total = res.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    addRole() {
      this.btnLoading = true;
      const params = {
        name: this.roleInfo.name,
        desc: this.roleInfo.desc,
        status: this.roleInfo.status ? 1 : 0,
      };
      if (this.edit) {
        createRole(params)
          .then((res) => {
            this.$Message.success("添加成功");
            this.addModal = false;
            this.btnLoading = false;
            this.params.current = 1;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      } else {
        updateRole(Object.assign({}, params, { id: this.roleInfo.id }))
          .then((res) => {
            this.$Message.success("编辑成功");
            this.addModal = false;
            this.btnLoading = false;
            this.getData();
          })
          .catch(() => {
            this.btnLoading = false;
          });
      }
    },
    ok() {
      this.$refs.create.validate((valid) => {
        if (valid) {
          this.addRole();
          // this.getData()
        } else {
          this.addModal = true;
          // this.$Message.error('填写错误，保存失败！')
          return;
        }
      });
    },
    handleRole(info) {
      this.rloeName = info.name;
      this.showPermission = true;
      this.myactionIds = [];
      this.mymenuIds = [];
      this.roleEditId = info.id;
      permissionInfo({ id: info.id })
        .then((res) => {
          var all = [
            {
              checked: false,
              children: res,
              expand: true,
              half_checked: false,
              level: 0,
              permission_type: 0,
              pid: "0",
              title: "全选",
              value: "0",
            },
          ];
          this.rolePermissionList = all;
          this.refreshgrops(all);
          this.menuIdsAsync(this.mymenuIds);
          this.actionIdsAsync(this.myactionIds);
        })
        .catch(() => {});
    },
    refreshgrops(item) {
      item.forEach((el) => {
        if (!el.checked && el.half_checked) {
          el.isIndeterminate = true;
        }
        if (el.checked === true && el.permission_type === 2) {
          this.myactionIds.push(el.value);
        } else if (
          (el.checked == true || el.isIndeterminate) &&
          el.permission_type === 1
        ) {
          this.mymenuIds.push(el.value);
        }
        if (el.children) {
          this.refreshgrops(el.children);
        }
      });
      if (this.mymenuIds.length > 0) {
        this.rolePermissionList[0].half_checked = true;
        this.rolePermissionList[0].isIndeterminate = true;
      }
      // }
    },
    handleEditRole() {
      this.btnLoading = true;
      let params = {
        id: this.roleEditId,
        menu_ids: this.menuIds.length > 0 ? this.menuIds : [""],
        action_ids: this.actionIds.length ? this.actionIds : [""],
      };
      updatePermission(params)
        .then(() => {
          this.$Message.success("设置成功");
          this.btnLoading = false;
          this.showPermission = false;
        })
        .catch(() => {
          this.btnLoading = false;
        });
    },
  },
};
</script>
<style lang="less" scoped>
.pre-drawer-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  width: 800px;
  box-sizing: border-box;
  border-top: 1px solid #e8e8e8;
  padding: 10px 20px;
  text-align: right;
  background: #fff;
}
.role {
  padding-bottom: 60px;
}
</style>
